package action;

import java.security.MessageDigest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import form.LoginForm;
import model.IUsers;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import service.ServiceManager;
import service.UsersService;
import model.UserPrincipal;

public class LoginAction extends ConnectionAwareAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String target = ForwardActionTo.ERROR;
		LoginForm loginForm = (LoginForm) form;

		try{
			String name_user = loginForm.getUserName();
			String pass_user = loginForm.getPassword();
			
			MessageDigest md5 ;        
		    StringBuffer  hexString = new StringBuffer();
			
		    md5 = MessageDigest.getInstance("md5");
            md5.reset();
            md5.update(pass_user.getBytes());
            
            byte messageDigest[] = md5.digest();
            
            for (int i = 0; i < messageDigest.length; i++) {
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }
			UsersService usersService = ServiceManager.getDefault().getUsersService();
			IUsers logins = null;
				
				if (name_user != null && hexString.toString() !=null) {
					logins = usersService.getUsers(name_user,hexString.toString());
				}
				if (logins.getName_user() != null) {
					target = ForwardActionTo.SUCCESS;
					request.setAttribute("message", loginForm.getUserName());
					HttpSession session = request.getSession(true);
					session.setAttribute("auth", new UserPrincipal(loginForm.getUserName(), loginForm.getPassword()));
				} else {
					ActionMessages errors = new ActionMessages();
					errors.add("invalidUserName", new ActionMessage("error.login.fail", loginForm.getUserName()));
					saveErrors(request,errors);
        	 		return mapping.findForward(ForwardActionTo.ERROR);
				}
		  }catch(Exception ex){
	        	target = ForwardActionTo.ERROR;
		  }
		return mapping.findForward(target);
	}
}
